<template>
  <div class="dashboard">
    <!-- 第一行：今日概况、昨日概况、快捷方式 -->
    <el-row :gutter="20" class="top-row">
      <!-- 今日概况 -->
      <el-col :span="8">
        <el-card class="overview-card">
          <div class="card-title">今日概况</div>
          <div class="overview-grid">
            <div class="overview-item">
              <div class="item-label">单据数量</div>
              <div class="item-value">{{ indodernum }}</div>
              <el-tag type="success" size="small">入库</el-tag>
            </div>
            <div class="overview-item">
              <div class="item-label">单据数量</div>
              <div class="item-value">{{ outodernum }}</div>
              <el-tag type="warning" size="small">出库</el-tag>
            </div>
            <div class="overview-item">
              <div class="item-label">入库数量</div>
              <div class="item-value">{{ indnum }}</div>
            </div>
            <div class="overview-item">
              <div class="item-label">出库数量</div>
              <div class="item-value">{{ outnum }}</div>
            </div>
            <div class="overview-item">
              <div class="item-label">入库金额</div>
              <div class="item-value">{{ indmoney.toFixed(2) }}</div>
            </div>
            <div class="overview-item">
              <div class="item-label">出库金额</div>
              <div class="item-value">{{ outmoney.toFixed(2) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 昨日概况 -->
      <el-col :span="8">
        <el-card class="overview-card">
          <div class="card-title">昨日概况</div>
          <div class="overview-grid">
            <div class="overview-item">
              <div class="item-label">单据数量</div>
              <div class="item-value">{{ yesterdayIndodernum }}</div>
              <el-tag type="success" size="small">入库</el-tag>
            </div>
            <div class="overview-item">
              <div class="item-label">单据数量</div>
              <div class="item-value">{{ yesterdayOutodernum }}</div>
              <el-tag type="warning" size="small">出库</el-tag>
            </div>
            <div class="overview-item">
              <div class="item-label">入库数量</div>
              <div class="item-value">{{ yesterdayIndnum }}</div>
            </div>
            <div class="overview-item">
              <div class="item-label">出库数量</div>
              <div class="item-value">{{ yesterdayOutnum }}</div>
            </div>
            <div class="overview-item">
              <div class="item-label">入库金额</div>
              <div class="item-value">{{ yesterdayIndmoney.toFixed(2) }}</div>
            </div>
            <div class="overview-item">
              <div class="item-label">出库金额</div>
              <div class="item-value">{{ yesterdayOutmoney.toFixed(2) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 快捷方式 -->
      <el-col :span="8">
        <el-card class="quick-card">
          <div class="card-title">快捷方式</div>
          <div class="quick-actions-grid">
            <div class="quick-item" @click="navigateTo('instock')">
              <el-icon><Plus /></el-icon>
              <span>入库管理</span>
            </div>
            <div class="quick-item" @click="navigateTo('outstock')">
              <el-icon><Minus /></el-icon>
              <span>出库管理</span>
            </div>
            <div class="quick-item" @click="navigateTo('check')">
              <el-icon><Box /></el-icon>
              <span>库存盘点</span>
            </div>
            <div class="quick-item" @click="navigateTo('allot')">
              <el-icon><Edit /></el-icon>
              <span>库存调拨</span>
            </div>
            <div class="quick-item" @click="navigateTo('stockwarning')">
              <el-icon><Warning /></el-icon>
              <span>库存预警</span>
            </div>
            <div class="quick-item" @click="navigateTo('info')">
              <el-icon><Setting /></el-icon>
              <span>系统信息</span>
            </div>
            <div class="quick-item" @click="navigateTo('purchase')">
              <el-icon><Document /></el-icon>
              <span>进货</span>
            </div>
            <div class="quick-item" @click="navigateTo('sale')">
              <el-icon><Document /></el-icon>
              <span>销售</span>
            </div>
            <div class="quick-item" @click="navigateTo('product')">
              <el-icon><Goods /></el-icon>
              <span>货品管理</span>
            </div>
            <div class="quick-item" @click="navigateTo('warehouse')">
              <el-icon><House /></el-icon>
              <span>仓库管理</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：库存数量占比、库存金额占比、代办事项 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 库存数量占比 -->
      <el-col :span="8">
        <el-card>
          <div class="card-title">库存数量占比</div>
          <div class="chart-container">
            <div id="quantityChart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 库存金额占比 -->
      <el-col :span="8">
        <el-card>
          <div class="card-title">库存金额占比</div>
          <div class="chart-container">
            <div id="amountChart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 代办事项 -->
      <el-col :span="8">
        <el-card>
          <div class="card-title">代办事项</div>
          <div class="todo-section">
            <div class="todo-category">
              <div class="category-title">◆ 待审核</div>
              <div class="todo-grid">
                <div class="todo-item" @click="navigateWithQuery('instock', { status: 'auditing' })">
                  <span>入库单据</span>
                  <span class="count">{{ pendingInstock }}</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('outstock', { status: 'auditing' })">
                  <span>出库单据</span>
                  <span class="count">{{ pendingOutstock }}</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('allot', { status: 'auditing' })">
                  <span>调拨单据</span>
                  <span class="count">{{ pendingAllot }}</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('check', { status: 'auditing' })">
                  <span>盘点单据</span>
                  <span class="count">0</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('purchase', { status: 'auditing' })">
                  <span>进货单据</span>
                  <span class="count">{{ pendingPurchase }}</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('sale', { status: 'auditing' })">
                  <span>销售单据</span>
                  <span class="count">{{ pendingSale }}</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('purchasereturn', { status: 'auditing' })">
                  <span>进货退货</span>
                  <span class="count">{{ pendingPurchaseReturn }}</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('salereturn', { status: 'auditing' })">
                  <span>销售退货</span>
                  <span class="count">{{ pendingSaleReturn }}</span>
                </div>
              </div>
            </div>
            <div class="todo-category">
              <div class="category-title">◆ 待执行</div>
              <div class="todo-grid">
                <div class="todo-item" @click="navigateWithQuery('instock', { status: 'waiting' })">
                  <span>待入库</span>
                  <span class="count">{{ waitingInstock }}</span>
                </div>
                <div class="todo-item" @click="navigateWithQuery('outstock', { status: 'waiting' })">
                  <span>待出库</span>
                  <span class="count">{{ waitingOutstock }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="warning-section">
            <div class="warning-title">预警信息</div>
            <div class="warning-items">
              <div class="warning-item green" @click="navigateWithQuery('stockwarning', { type: 'high' })">
                <div class="warning-icon">↑</div>
                <div class="warning-text">
                  <div>库存数量上限</div>
                  <div class="warning-count">{{ highLimitCount }} 种</div>
                </div>
              </div>
              <div class="warning-item red" @click="navigateWithQuery('stockwarning', { type: 'low' })">
                <div class="warning-icon">↓</div>
                <div class="warning-text">
                  <div>库存数量下限</div>
                  <div class="warning-count">{{ lowLimitCount }} 种</div>
                </div>
              </div>
              <div class="warning-item orange" @click="navigateWithQuery('selectShelflife', { type: 'near_expired' })">
                <div class="warning-icon">📦</div>
                <div class="warning-text">
                  <div>临期货品</div>
                  <div class="warning-count">{{ nearExpiredCount }} 种</div>
                </div>
              </div>
              <div class="warning-item red" @click="navigateWithQuery('selectShelflife', { type: 'expired' })">
                <div class="warning-icon">⚠</div>
                <div class="warning-text">
                  <div>到期货品</div>
                  <div class="warning-count">{{ expiredCount }} 种</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第三行：入库统计图表 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="24">
        <el-card>
          <div class="card-title">
            入库统计
            <div class="time-tabs">
              <el-button 
                :type="activeInstockTime === '7' ? 'primary' : ''" 
                size="small"
                @click="switchInstockTime('7')"
              >
                最近7天
              </el-button>
              <el-button 
                :type="activeInstockTime === '30' ? 'primary' : ''" 
                size="small"
                @click="switchInstockTime('30')"
              >
                最近30天
              </el-button>
              <el-button 
                :type="activeInstockTime === '365' ? 'primary' : ''" 
                size="small"
                @click="switchInstockTime('365')"
              >
                最近一年
              </el-button>
            </div>
          </div>
          <div id="instockChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第四行：出库统计图表 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="24">
        <el-card>
          <div class="card-title">
            出库统计
            <div class="time-tabs">
              <el-button 
                :type="activeOutstockTime === '7' ? 'primary' : ''" 
                size="small"
                @click="switchOutstockTime('7')"
              >
                最近7天
              </el-button>
              <el-button 
                :type="activeOutstockTime === '30' ? 'primary' : ''" 
                size="small"
                @click="switchOutstockTime('30')"
              >
                最近30天
              </el-button>
              <el-button 
                :type="activeOutstockTime === '365' ? 'primary' : ''" 
                size="small"
                @click="switchOutstockTime('365')"
              >
                最近一年
              </el-button>
            </div>
          </div>
          <div id="outstockChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第五行：入库排名、出库排名、系统消息 -->
    <el-row :gutter="20" class="table-row">
      <!-- 入库排名 -->
      <el-col :span="8">
        <el-card>
          <div class="card-title">入库排名</div>
          <el-table :data="instockRanking" size="small" :show-header="true" height="358">
            <el-table-column prop="rank" label="排名" width="60" align="center">
              <template #default="scope">
                <el-tag :type="getRankType(scope.row.rank)" size="small">
                  {{ scope.row.rank }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="货品名称"></el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" align="center"></el-table-column>
            <el-table-column label="金额" width="100" align="center">
              <template #default="scope">
                {{ Number(scope.row.amount).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="times" label="入库次数" width="80" align="center"></el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 出库排名 -->
      <el-col :span="8">
        <el-card>
          <div class="card-title">出库排名</div>
          <el-table :data="outstockRanking" size="small" :show-header="true" height="358">
            <el-table-column prop="rank" label="排名" width="60" align="center">
              <template #default="scope">
                <el-tag :type="getRankType(scope.row.rank)" size="small">
                  {{ scope.row.rank }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="货品名称"></el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" align="center"></el-table-column>
            <el-table-column label="金额" width="100" align="center">
              <template #default="scope">
                {{ Number(scope.row.amount).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="times" label="出库次数" width="80" align="center"></el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 系统消息 -->
      <el-col :span="8">
        <el-card>
          <div class="card-title">
            系统消息
            <span class="more-link" @click="goToInfoList">更多</span>
          </div>
          <div class="message-list">
            <div 
              class="message-item" 
              v-for="(msg, index) in systemMessages" 
              :key="index"
              @click="handleMessageClick"
            >
              <div class="message-dot"></div>
              <div class="message-content">
                <div class="message-text">{{ msg.content }}</div>
                <div class="message-time">{{ msg.time }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { useRouter, useRoute } from 'vue-router'
import {ref,reactive,onMounted} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox  } from 'element-plus'; //提示信息
import * as echarts from 'echarts';
export default {
    setup(){
        const router = useRouter();
        const route = useRoute();
        const user = JSON.parse(sessionStorage.getItem("user"));

         // 时间转换
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hour = date.getHours();
            const minute = date.getMinutes();
            const second = date.getSeconds();

            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        }


         //#region 今日概括和昨日概括

        //今日数据
        const outodernum=ref(0); //出库单据数量
        const outnum=ref(0);//出库数量
        const outmoney=ref(0);//出库金额
        const indodernum=ref(0);//入库单据数量
        const indnum=ref(0);//入库数量  
        const indmoney=ref(0);//入库金额

        //昨日数据
        const yesterdayOutodernum=ref(0); //昨日出库单据数量
        const yesterdayOutnum=ref(0);//昨日出库数量
        const yesterdayOutmoney=ref(0);//昨日出库金额
        const yesterdayIndodernum=ref(0);//昨日入库单据数量
        const yesterdayIndnum=ref(0);//昨日入库数量  
        const yesterdayIndmoney=ref(0);//昨日入库金额

        // 获取今日和昨日统计数据
        async function getDashboardStats() {
            try {
                const response = await http.get('/Dashboard/GetDashboardStats');
                const data = response.data;
                
                // 今日数据
                outodernum.value = data.todayOutOrderCount || 0;
                outnum.value = data.todayOutNum || 0;
                outmoney.value = data.todayOutMoney || 0;
                indodernum.value = data.todayInOrderCount || 0;
                indnum.value = data.todayInNum || 0;
                indmoney.value = data.todayInMoney || 0;
                
                // 昨日数据
                yesterdayOutodernum.value = data.yesterdayOutOrderCount || 0;
                yesterdayOutnum.value = data.yesterdayOutNum || 0;
                yesterdayOutmoney.value = data.yesterdayOutMoney || 0;
                yesterdayIndodernum.value = data.yesterdayInOrderCount || 0;
                yesterdayIndnum.value = data.yesterdayInNum || 0;
                yesterdayIndmoney.value = data.yesterdayInMoney || 0;
                
            } catch (error) {
                console.error('获取统计数据失败:', error);
                ElMessage.error('获取统计数据失败');
            }
        }

        //#endregion
       

         //#region 待办事项相关

        // 待办事项数据
        const pendingInstock = ref(0);        // 待审核入库单据
        const pendingOutstock = ref(0);       // 待审核出库单据
        const pendingAllot = ref(0);          // 待审核调拨单据
        const pendingPurchase = ref(0);       // 待审核进货单据
        const pendingSale = ref(0);           // 待审核销售单据
        const pendingPurchaseReturn = ref(0); // 待审核进货退货
        const pendingSaleReturn = ref(0);     // 待审核销售退货
        const waitingInstock = ref(0);        // 待执行入库
        const waitingOutstock = ref(0);       // 待执行出库

        // 获取待办事项统计数据
        async function getTodoStats() {
            try {
                const response = await http.get('/Dashboard/GetTodoStats');
                const data = response.data;
                
                // 待办事项数据
                pendingInstock.value = data.pendingInstock || 0;
                pendingOutstock.value = data.pendingOutstock || 0;
                pendingAllot.value = data.pendingAllot || 0;
                pendingPurchase.value = data.pendingPurchase || 0;
                pendingSale.value = data.pendingSale || 0;
                pendingPurchaseReturn.value = data.pendingPurchaseReturn || 0;
                pendingSaleReturn.value = data.pendingSaleReturn || 0;
                waitingInstock.value = data.waitingInstock || 0;
                waitingOutstock.value = data.waitingOutstock || 0;
                
            } catch (error) {
                console.error('获取待办事项失败:', error);
                ElMessage.error('获取待办事项失败');
            }
        }

        //#endregion

       
         //#region 预警信息相关


        // 预警信息数据
        const highLimitCount = ref(0);      // 库存上限预警
        const lowLimitCount = ref(0);       // 库存下限预警
        const expiredCount = ref(0);        // 到期货品
        const nearExpiredCount = ref(0);    // 临期货品

        // 获取预警信息统计数据
        async function getWarningStats() {
            try {
                const response = await http.get('/Dashboard/GetWarningStats');
                const data = response.data;
                
                highLimitCount.value = data.highLimitCount || 0;
                lowLimitCount.value = data.lowLimitCount || 0;
                expiredCount.value = data.expiredCount || 0;
                nearExpiredCount.value = data.nearExpiredCount || 0;
                
            } catch (error) {
                console.error('获取预警信息失败:', error);
                ElMessage.error('获取预警信息失败');
            }
        }

        //#endregion

        
         //#region 仓库库存占比相关


        // 仓库库存统计数据
        const warehouseStockStats = ref([]);
        const totalStockCount = ref(0);
        const totalStockAmount = ref(0);

        // 获取仓库库存统计数据
        async function getWarehouseStockStats() {
            try {
                const response = await http.get('/Dashboard/GetWarehouseStockStats');
                const data = response.data;
                
                warehouseStockStats.value = data.warehouseStats || [];
                totalStockCount.value = data.totalCount || 0;
                totalStockAmount.value = data.totalAmount || 0;
                
                // 初始化图表
                initQuantityChart();
                initAmountChart();
                
            } catch (error) {
                console.error('获取仓库库存统计失败:', error);
                ElMessage.error('获取仓库库存统计失败');
            }
        }

        // 初始化库存数量占比图表
        function initQuantityChart() {
            const chartDom = document.getElementById('quantityChart');
            if (!chartDom) return;
            
            const myChart = echarts.init(chartDom);
            
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    right: 10,
                    top: 20,
                    bottom: 20,
                    formatter: function(name) {
                        const item = warehouseStockStats.value.find(x => x.warehouseName === name);
                        return item ? `${name}    ${item.stockCount}` : name;
                    }
                },
                series: [
                    {
                        name: '库存数量',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        center: ['40%', '50%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: false  // 禁用悬浮高亮显示
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: warehouseStockStats.value.map(item => ({
                            value: item.stockCount,
                            name: item.warehouseName
                        }))
                    }
                ],
                graphic: {
                    elements: [{
                        type: 'text',
                        left: '35%',
                        top: 'center',
                        style: {
                            text: totalStockCount.value + '\n总数量',
                            textAlign: 'center',
                            fill: '#333',
                            fontSize: 16,
                            fontWeight: 'bold'
                        }
                    }]
                }
            };
            
            myChart.setOption(option);
        }

        // 初始化库存金额占比图表
        function initAmountChart() {
            const chartDom = document.getElementById('amountChart');
            if (!chartDom) return;
            
            const myChart = echarts.init(chartDom);
            
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    right: 10,
                    top: 20,
                    bottom: 20,
                    formatter: function(name) {
                        const item = warehouseStockStats.value.find(x => x.warehouseName === name);
                        return item ? `${name}    ${item.stockAmount.toFixed(2)}` : name;
                    }
                },
                series: [
                    {
                        name: '库存金额',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        center: ['40%', '50%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: false  // 禁用悬浮高亮显示
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: warehouseStockStats.value.map(item => ({
                            value: item.stockAmount,
                            name: item.warehouseName
                        }))
                    }
                ],
                graphic: {
                    elements: [{
                        type: 'text',
                        left: '35%',
                        top: 'center',
                        style: {
                            text: totalStockAmount.value.toFixed(2) + '\n总金额',
                            textAlign: 'center',
                            fill: '#333',
                            fontSize: 16,
                            fontWeight: 'bold'
                        }
                    }]
                }
            };
            
            myChart.setOption(option);
        }

        //#endregion


        //#region 入库统计相关
        // 入库统计相关
        const instockStats = ref([]);
        const activeInstockTime = ref('7');

        // 获取入库统计数据
        async function getInstockStats(timeType = '7') {
            try {
                const response = await http.get(`/Dashboard/GetInstockStats?timeType=${timeType}`);
                instockStats.value = response.data;
                activeInstockTime.value = timeType;
                
                // 初始化入库统计图表
                initInstockChart();
                
            } catch (error) {
                console.error('获取入库统计失败:', error);
                ElMessage.error('获取入库统计失败');
            }
        }

        // 初始化入库统计图表
        function initInstockChart() {
            const chartDom = document.getElementById('instockChart');
            if (!chartDom) return;
            
            const myChart = echarts.init(chartDom);
            
            const dates = instockStats.value.map(item => item.date);
            const orderCounts = instockStats.value.map(item => item.orderCount);
            const amounts = instockStats.value.map(item => item.totalAmount);
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['入库数量', '入库金额']
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '入库数量',
                        position: 'left',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        name: '入库金额',
                        position: 'right',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }
                ],
                series: [
                    {
                        name: '入库数量',
                        type: 'bar',
                        data: orderCounts,
                        itemStyle: {
                            color: '#5470c6'
                        }
                    },
                    {
                        name: '入库金额',
                        type: 'line',
                        yAxisIndex: 1,
                        data: amounts,
                        itemStyle: {
                            color: '#91cc75'
                        }
                    }
                ]
            };
            
            myChart.setOption(option);
        }

        // 切换入库统计时间范围
        function switchInstockTime(timeType) {
            getInstockStats(timeType);
        }
        //#endregion 

        
        //#region 出库统计相关
        // 出库统计相关
        const outstockStats = ref([]);
        const activeOutstockTime = ref('7');

        // 获取出库统计数据
        async function getOutstockStats(timeType = '7') {
            try {
                const response = await http.get(`/Dashboard/GetOutstockStats?timeType=${timeType}`);
                outstockStats.value = response.data;
                activeOutstockTime.value = timeType;
                
                // 初始化出库统计图表
                initOutstockChart();
                
            } catch (error) {
                console.error('获取出库统计失败:', error);
                ElMessage.error('获取出库统计失败');
            }
        }

        // 初始化出库统计图表
        function initOutstockChart() {
            const chartDom = document.getElementById('outstockChart');
            if (!chartDom) return;
            
            const myChart = echarts.init(chartDom);
            
            const dates = outstockStats.value.map(item => item.date);
            const orderCounts = outstockStats.value.map(item => item.orderCount);
            const amounts = outstockStats.value.map(item => item.totalAmount);
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    data: ['出库数量', '出库金额']
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '出库数量',
                        position: 'left',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        name: '出库金额',
                        position: 'right',
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }
                ],
                series: [
                    {
                        name: '出库数量',
                        type: 'bar',
                        data: orderCounts,
                        itemStyle: {
                            color: '#fac858'
                        }
                    },
                    {
                        name: '出库金额',
                        type: 'line',
                        yAxisIndex: 1,
                        data: amounts,
                        itemStyle: {
                            color: '#91cc75'
                        }
                    }
                ]
            };
            
            myChart.setOption(option);
        }

        // 切换出库统计时间范围
        function switchOutstockTime(timeType) {
            getOutstockStats(timeType);
        }
        //#endregion


        //#region 排名相关
        // 入库排名数据
        const instockRanking = ref([]);
        // 出库排名数据
        const outstockRanking = ref([]);

        // 获取入库排名数据
        async function getInstockRanking() {
            try {
                const response = await http.get('/Dashboard/GetInstockRanking');
                instockRanking.value = response.data;
            } catch (error) {
                console.error('获取入库排名失败:', error);
                ElMessage.error('获取入库排名失败');
            }
        }

        // 获取出库排名数据
        async function getOutstockRanking() {
            try {
                const response = await http.get('/Dashboard/GetOutstockRanking');
                outstockRanking.value = response.data;
            } catch (error) {
                console.error('获取出库排名失败:', error);
                ElMessage.error('获取出库排名失败');
            }
        }

        // 获取排名标签类型
        function getRankType(rank) {
            if (rank <= 3) {
                return rank === 1 ? 'danger' : rank === 2 ? 'warning' : 'success';
            }
            return 'info';
        }
        //#endregion

        
        //#region 系统消息相关
        // 系统消息数据
        const systemMessages = ref([]);

        // 获取系统消息数据
        async function getSystemMessages() {
            try {
                const response = await http.get('/Dashboard/GetSystemMessages');
                systemMessages.value = response.data.map(item => ({
                    content: item.info_text,
                    time: formatDateTime(new Date(item.info_time))
                }));
            } catch (error) {
                console.error('获取系统消息失败:', error);
                ElMessage.error('获取系统消息失败');
            }
        }

        // 跳转到信息列表页面
        function goToInfoList() {
            router.push({ name: 'info' });
        }

        // 点击消息行跳转到信息列表
        function handleMessageClick() {
            goToInfoList();
        }
        //#endregion


         // 快捷方式导航
        function navigateTo(path) {
            router.push('/main/' + path);
        }

        function navigateWithQuery(path, query) {
            if (path) {
                router.push({ path: `/main/${path}`, query: query });
            }
        }



        // 挂载时获取数据
        onMounted(() => {
            getDashboardStats();
            getTodoStats();
            getWarningStats();
            getWarehouseStockStats();
            getInstockStats();
            getOutstockStats();
            getInstockRanking();
            getOutstockRanking();
            getSystemMessages(); // 添加系统消息数据获取
        });

        return {
            outodernum,
            outnum,
            outmoney,
            indodernum,
            indnum,
            indmoney,
            yesterdayOutodernum,
            yesterdayOutnum,
            yesterdayOutmoney,
            yesterdayIndodernum,
            yesterdayIndnum,
            yesterdayIndmoney,
            // 待办事项数据
            pendingInstock,
            pendingOutstock,
            pendingAllot,
            pendingPurchase,
            pendingSale,
            pendingPurchaseReturn,
            pendingSaleReturn,
            waitingInstock,
            waitingOutstock,
            // 预警信息数据
            highLimitCount,
            lowLimitCount,
            expiredCount,
            nearExpiredCount,
            // 仓库库存占比数据
            warehouseStockStats,
            totalStockCount,
            totalStockAmount,
            // 入库统计数据
            instockStats,
            activeInstockTime,
            // 出库统计数据
            outstockStats,
            activeOutstockTime,
            // 排名数据
            instockRanking,
            outstockRanking,
            // 方法
            navigateTo,
            navigateWithQuery,
            getTodoStats,
            getWarningStats,
            getWarehouseStockStats,
            getInstockStats,
            switchInstockTime,
            getOutstockStats,
            switchOutstockTime,
            getInstockRanking,
            getOutstockRanking,
            getRankType,
            systemMessages,
            getSystemMessages,
            goToInfoList,
            handleMessageClick
        }
    }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;
}

.top-row, .chart-row, .stats-row, .table-row {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  text-align: center;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.overview-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  font-size: 13px;
  gap: 8px;
}

.item-label {
  color: #606266;
}

.item-value {
  font-weight: bold;
  color: #303133;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
}

.quick-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-item:hover {
  background-color: #e9ecef;
}

.quick-item .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #409eff;
}

.quick-item span {
  font-size: 12px;
  color: #606266;
}

.todo-section {
  margin-bottom: 20px;
}

.category-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
}

.todo-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  margin-bottom: 15px;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.todo-item:hover {
  background-color: #e9ecef;
}

.count {
  font-weight: bold;
  color: #f56c6c;
}

.warning-section {
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
}

.warning-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
}

.warning-items {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.warning-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
}

.warning-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.warning-item.green {
  background-color: #f0f9ff;
  border-color: #67c23a;
}

.warning-item.red {
  background-color: #fef0f0;
  border-color: #f56c6c;
}

.warning-item.orange {
  background-color: #fdf6ec;
  border-color: #e6a23c;
}

.warning-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 20px;
  border-radius: 50%;
}

.warning-text {
  flex: 1;
}

.warning-count {
  font-weight: bold;
  font-size: 18px;
}

.time-tabs {
  display: flex;
  gap: 5px;
}

.message-list {
  height: 358px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.message-dot {
  width: 6px;
  height: 6px;
  background-color: #f56c6c;
  border-radius: 50%;
  margin-right: 10px;
  margin-top: 6px;
}

.message-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
  overflow: hidden;
}

.message-text {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-time {
  font-size: 12px;
  color: #909399;
  flex-shrink: 0;
}

.more-link {
  font-size: 12px;
  color: #409eff;
  cursor: pointer;
}

.chart-container {
  position: relative;
  height: 650px;
}

#quantityChart, #amountChart {
  height: 650px !important;
}

.more-link {
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
}

.more-link:hover {
  color: #66b1ff;
}

.message-item {
  cursor: pointer;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.message-item:hover {
  background-color: #f5f7fa;
}

.message-item:last-child {
  border-bottom: none;
}
</style>






